import {
    createSlice
} from "@reduxjs/toolkit";
import {getFindByParentId} from "@/api/dict";
import {useSelector} from "react-redux";

const findInfo:any = (arr:any,id:number)=>{
    let info;
    for(let i = 0;i<arr.length;i++){
        if(arr[i].id === id){
            info = arr[i];
        }else if(arr[i].children && arr[i].children.length > 0){
            info = findInfo(arr[i].children,id);
        }
        if(info){
            break;
        }
    }
     return info
}


const dictSlice = createSlice({
    name:"dict",
    initialState:{
        dictList:[],
        loading:false
    },
    reducers:{
        upLoading(state,{payload}){
            state.loading = payload
        },
        upDictList(state,{payload}){
            const info:any = findInfo(state.dictList,payload.parentId)
            if(info){
                info.children = payload.dictList
            }else {
                state.dictList = payload.dictList
            }
        }
    }
})
export  const {upDictList,upLoading} = dictSlice.actions
export const getFindByParentIdAsync = (parentId:number)=>{
    return async (dispatch:any)=>{
        dispatch(upLoading(true))
        const result = await getFindByParentId(parentId)
        dispatch(upDictList({
            dictList: result.data.map((item:any)=>{
                if(item.hasChildren){
                    item.children = [];
                }
                return item;
            }),
            parentId
        }))
        dispatch(upLoading(false))
    }
}
export const useSelectorDict = ()=>useSelector((state:any)=>state.dict)
export  default dictSlice.reducer